package main

import (
	"context"
	"fmt"
	"os"
	"strings"
	"time"

	"../kp/prowatcher/pb"
	"github.com/op/go-logging"
	"google.golang.org/grpc"
	"gopkg.in/alecthomas/kingpin.v2"
)

var (
	user     = kingpin.Flag("user", "user name").Default("test").Short('u').String()
	token    = kingpin.Flag("token", "token string").Required().Short('t').String()
	wconf    = kingpin.Flag("conf", "conf file.").Required().Short('c').String()
	tags     = kingpin.Flag("tag", "tag key=value.").StringMap()
	log_file = kingpin.Flag("log", "log file.").Short('l').String()
	log      = logging.MustGetLogger("pwkeeper")
)

func main() {
	kingpin.Parse()
	if *log_file == "" {
		bk := logging.NewLogBackend(os.Stderr, "", 0)
		logging.SetBackend(bk)
	} else {
		file, err := os.OpenFile(*log_file, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
		if err != nil {
			log.Errorf("open log file %s , error: ", *log_file, err)
		}
		defer file.Close()
		bk := logging.NewLogBackend(file, "", 0)
		logging.SetBackend(bk)
	}

	fmt.Println("===================================================================================")
	var host string
	fmt.Println("#please input host:")
	fmt.Scanln(&host)
	if host == "exit" {
		os.Exit(0)
	}
	conn, err := grpc.Dial(fmt.Sprintf("%s:9221", host), grpc.WithInsecure())
	if err != nil {
		log.Error(err)
		os.Exit(2)
	}
	defer conn.Close()
	cli := pb.NewWatcherServiceClient(conn)
	tk := pb.Token{User: *user, Token: *token}

	pw, perr := Newpwatcher(&tk, &cli, *wconf)
	if perr != nil {
		log.Errorf("error: %v\n", perr)
		os.Exit(2)
	}

	var procname string
	fmt.Println("#please input [procname]:")
	fmt.Scanln(&procname)
	clk, ok := pw.clks[procname]
	if !ok {
		log.Errorf("proc %s cmdlink not found", procname)
		os.Exit(2)
	}
	var knode KeeperNode
	/*snode := &SerialNode{}
	for i := 0; i < len(clk.Cmdlink); i++ {
		cmd := clk.Cmdlink[i]
		cmdArgs := strings.Split(clk.CmdArgs[cmd], " ")
		knode = &ExecNode{pw: pw, procName: procname, cmdName: cmd, cmdArgs: cmdArgs, judge: clk.Judge[cmd]}
		snode.nodes = append(snode.nodes, knode)
	}
	snode.state = *NewStateGroup(len(clk.Cmdlink))
	snode.Do(context.Background())
	tick := time.Tick(time.Second * 1)
	for {
		<-tick
		if snode.Finished() {
			_, err := snode.Result()
			if err != nil {
				log.Error(err)
			} else {
				log.Info("success!!")
			}
			break
		} else {
			log.Info("running")
		}
	}*/
	snode := &ParallelNode{}
	for i := 0; i < len(clk.Cmdlink); i++ {
		cmd := clk.Cmdlink[i]
		cmdArgs := strings.Split(clk.CmdArgs[cmd], " ")
		knode = &ExecNode{pw: pw, procName: procname, cmdName: cmd, cmdArgs: cmdArgs, judge: clk.Judge[cmd]}
		snode.nodes = append(snode.nodes, knode)
	}
	snode.state = *NewStateGroup(len(clk.Cmdlink))
	snode.parallelSize = len(clk.Cmdlink)
	snode.errorTolerance = 0
	snode.Do(context.Background())
	tick := time.Tick(time.Second * 1)
	for {
		<-tick
		if snode.Finished() {
			_, err := snode.Result()
			if err != nil {
				log.Error(err)
			} else {
				log.Info("success!!")
			}
			break
		} else {
			log.Info("running")
		}
	}
}
